package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
)

// 获取校车行程信息
func GetTravelInfo(p map[string]interface{}) *models.Travel {
	o := orm.NewOrm()
	travel := &models.Travel{}
	qs := o.QueryTable("Travel")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["sn"]; ok {
		qs = qs.Filter("sn", p["sn"])
	}
	if _, ok := p["deviceId"]; ok {
		qs = qs.Filter("device_id", p["deviceId"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	qs.OrderBy("-id").One(travel)
	return travel
}

// 添加校车行程信息
func AddTravel(input url.Values) (int64, error) {
	o := orm.NewOrm()
	travel := &models.Travel{}

	sn := utils.UniqueId()
	p := map[string]interface{}{}
	p["sn"] = sn
	travelInfo := GetTravelInfo(p)
	for travelInfo.Id > 0 {
		sn = utils.UniqueId()
		p = map[string]interface{}{}
		p["sn"] = sn
		travelInfo = GetTravelInfo(p)
	}
	travel.Sn = sn

	device := &models.Device{}
	if _, ok := input["device_id"]; ok {
		device.Id = utils.Atoi64(input["device_id"][0])
		o.Read(device)
	}
	travel.Device = device

	if _, ok := input["status"]; ok {
		travel.Status, _ = strconv.Atoi(input["status"][0])
	}

	return o.Insert(travel)
}

// 修改校车行程信息
func EditTravel(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("Travel").Filter("id", input["id"][0]).Update(p)
}

// 获取校车行程列表
func GetTravelList(p map[string]interface{}) (int64, []*models.Travel) {
	var travelList []*models.Travel
	o := orm.NewOrm()
	qs := o.QueryTable("Travel")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["studentId"]; ok {
		qs = qs.Filter("Students__Student__Id", p["studentId"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&travelList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, travel := range travelList {
			travel.StartTimeShow = travel.StartTime.Format("2006-01-02 15:04:05")
			travel.EndTimeShow = travel.EndTime.Format("2006-01-02 15:04:05")
		}
	}
	return totalCount, travelList
}
